package com.example.translateappjava.Activity.HomeFragmentActivity.Forum;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.translateappjava.DataBase.UserInfo; // 导入 UserInfo
import com.example.translateappjava.R;
import com.example.translateappjava.Service.ForumApiService.ApiClient;
import com.example.translateappjava.Service.ForumApiService.ApiService;
import com.example.translateappjava.Utils.ApiResponse;
import com.example.translateappjava.Utils.Post; // 导入修改后的 Post

import java.time.Instant; // 使用 java.time.Instant

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CreatePostActivity extends AppCompatActivity {

    private static final String TAG = "CreatePostActivity";

    private EditText etTitle, etContent;
    private TextView tvCategory;
    private Button btnPublish;

    private String selectedCategory = "经验分享"; // Default category
    private String[] categories = {"营养食谱", "饮食日记", "健康科普", "经验分享"};

    private ApiService apiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_post);

        apiService = ApiClient.getClient().create(ApiService.class);

        setupToolbar();
        initViews();
        setupClickListeners();
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("发布帖子");
        }
    }

    private void initViews() {
        etTitle = findViewById(R.id.et_title);
        etContent = findViewById(R.id.et_content);
        tvCategory = findViewById(R.id.tv_category);
        btnPublish = findViewById(R.id.btn_publish);
        tvCategory.setText(selectedCategory);
    }

    private void setupClickListeners() {
        tvCategory.setOnClickListener(v -> showCategoryDialog());
        btnPublish.setOnClickListener(v -> attemptPublishPost());
    }

    private void showCategoryDialog() {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("选择分类");
        builder.setItems(categories, (dialog, which) -> {
            selectedCategory = categories[which];
            tvCategory.setText(selectedCategory);
        });
        builder.show();
    }

    private void attemptPublishPost() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();

        if (TextUtils.isEmpty(title)) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            etTitle.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            etContent.requestFocus();
            return;
        }

        UserInfo currentUser = UserInfo.getsUserInfo();
        String authorUsername = "未知用户";
        String authorAvatarUrl = "https://example.com/default_avatar.png"; // 默认头像URL

        if (currentUser != null) {
            if (currentUser.getNickname() != null && !currentUser.getNickname().equals("暂无~~~") && !currentUser.getNickname().isEmpty()) {
                authorUsername = currentUser.getNickname();
            } else if (currentUser.getName() != null && !currentUser.getName().equals("0") && !currentUser.getName().isEmpty()) {
                authorUsername = currentUser.getName();
            } else if (currentUser.getUsername() != null && !currentUser.getUsername().equals("0") && !currentUser.getUsername().isEmpty()) {
                authorUsername = currentUser.getUsername();
            }
            // 假设 UserInfo 也有头像信息，例如:
            // if (currentUser.getAvatarPath() != null && !currentUser.getAvatarPath().isEmpty()) {
            //    authorAvatarUrl = currentUser.getAvatarPath(); // 或者一个转换后的URL
            // }
            Log.d(TAG, "Author for new post: " + authorUsername);
        } else {
            Log.w(TAG, "UserInfo.sUserInfo is null! Cannot publish post without user info.");
            Toast.makeText(this, "用户未登录或信息丢失，无法发布", Toast.LENGTH_LONG).show();
            return; // 阻止发布
        }

        String currentTimeISO = Instant.now().toString(); // 当前UTC时间

        // 创建要发送到服务器的Post对象，serverId为null
        Post postToSendToServer = new Post(
                null,             // serverId (Long) 设置为 null，由服务器生成
                authorUsername,
                title,
                content,
                selectedCategory,
                currentTimeISO,   // time
                0,                // likeCount
                0,                // commentCount
                authorAvatarUrl,
                false,            // isLikedByCurrentUser
                false             // isFavoritedByUser
        );
        // localId 会在存入Room时自动生成，这里不需要设置

        publishPostToServer(postToSendToServer);
    }

    private void publishPostToServer(final Post postClientVersion) { // 重命名参数以区分
        btnPublish.setEnabled(false);
        // TODO: Show progress dialog (e.g., ProgressBar)

        // 注意：这里的 postClientVersion 的 serverId 是 null
        Call<ApiResponse<Post>> call = apiService.uploadPost(postClientVersion);
        call.enqueue(new Callback<ApiResponse<Post>>() {
            @Override
            public void onResponse(@NonNull Call<ApiResponse<Post>> call, @NonNull Response<ApiResponse<Post>> response) {
                btnPublish.setEnabled(true);
                // TODO: Hide progress dialog

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Post> apiResponse = response.body();
                    if (apiResponse.isSuccessful() && apiResponse.getData() != null) {
                        Toast.makeText(CreatePostActivity.this, "帖子发布成功", Toast.LENGTH_SHORT).show();
                        Post postFromServer = apiResponse.getData(); // 这个 postFromServer 应该包含服务器生成的 serverId (Long)

                        // 确保从服务器返回的Post对象有正确的作者信息。
                        // 如果服务器不返回作者信息，或者你想强制使用客户端的，可以在这里设置。
                        if (postFromServer.getUsername() == null || postFromServer.getUsername().isEmpty()) {
                            postFromServer.setUsername(postClientVersion.getUsername());
                        }
                        if (postFromServer.getAvatarUrl() == null || postFromServer.getAvatarUrl().isEmpty()) {
                            postFromServer.setAvatarUrl(postClientVersion.getAvatarUrl());
                        }
                        // 确保时间戳也正确（服务器通常会覆盖客户端的时间戳）
                        // postFromServer.setTime(postClientVersion.getTime()); // 通常不需要，服务器时间更权威

                        Intent resultIntent = new Intent();
                        resultIntent.putExtra("newPost", postFromServer); // 将带有服务器ID的Post对象传回
                        setResult(Activity.RESULT_OK, resultIntent);
                        Log.d(TAG, "Post published and returning to ForumActivity. ServerID: " + postFromServer.getServerId() + ", Author: " + postFromServer.getUsername());
                        finish();
                    } else {
                        String errorMessage = apiResponse.getMessage() != null ? apiResponse.getMessage() : "未知API错误";
                        Toast.makeText(CreatePostActivity.this, "发布失败: " + errorMessage, Toast.LENGTH_LONG).show();
                        Log.e(TAG, "API Error: " + errorMessage + " Code: " + apiResponse.getCode());
                    }
                } else {
                    String errorBodyString = "";
                    try {
                        if (response.errorBody() != null) {
                            errorBodyString = response.errorBody().string();
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "Error reading error body", e);
                    }
                    Toast.makeText(CreatePostActivity.this, "发布失败: " + response.code() + " " + response.message(), Toast.LENGTH_LONG).show();
                    Log.e(TAG, "Server Error: " + response.code() + " " + response.message() + " Body: " + errorBodyString);
                }
            }

            @Override
            public void onFailure(@NonNull Call<ApiResponse<Post>> call, @NonNull Throwable t) {
                btnPublish.setEnabled(true);
                // TODO: Hide progress dialog
                Toast.makeText(CreatePostActivity.this, "网络错误，发布失败: " + t.getMessage(), Toast.LENGTH_LONG).show();
                Log.e(TAG, "Network Failure: " + t.getMessage(), t);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}